//
//  YAYIMeViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/24.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYIMeViewController.h"
#import "YAYILoginViewController.h"
#import "YAYIPersoninfoViewController.h"
#import "YAYIAppSettingViewController.h"
#import "YAYIPerformanceViewController.h"
#import "YAYIMyHospitalViewController.h"
#import "YAYIMyQRCodeViewController.h"
#import "YAYISchedulingViewController.h"
#import "YAYIResumeViewController.h"
#import "YAYIAddResumeController.h"
#import "YAYISendResumeListViewController.h"
#import "YAYIUserCommentController.h"
#import "YAYICertificationViewController.h"

#import "YAYIMeHeadCell.h"
#import "YAYISettingCell.h"
#import "YAYISettingItemModel.h"
#import "YAYISettingSectionModel.h"
#import "YAYIUserinfoModel.h"

/** alertView提醒类型 tag */
typedef enum : NSUInteger {
    AlertTypeNotVerify = 100,
    AlertTypeNoResume = 200,
} AlertType;


@interface YAYIMeViewController () <UIAlertViewDelegate>


//@property (nonatomic,strong) NSMutableArray  *sectionArray; /**< section模型数组*/
@property (nonatomic, strong) YAYIUserinfoModel *userInfoModel;

/** 我的简历标示  myResumeV:审核状态 myResumeState:是否提交 */
@property (nonatomic, assign) NSInteger myResumeV;
@property (nonatomic, assign) NSInteger myResumeState;

@end

@implementation YAYIMeViewController

//- (NSMutableArray *)sectionArray
//{
//    if (nil == _sectionArray) {
//        _sectionArray = [NSMutableArray array];
//    }
//    return _sectionArray;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorInset = UIEdgeInsetsZero;
    if (SystemVersion >= 8.0) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, -10, 0);
    self.tableView.separatorColor = YAYICellLineColor;
    
    [self setupSection0];
    [self setupSection1];
    [self setupSection2];
    [self setupSection3];
    
//    [self createDataSource];
//    [self getResume];
    
    // 当登录状态改变刷新页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginStateChanged:) name:YAYILoginNotifyName object:nil];
}


- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    
    [self createDataSource];
    [self getIsHasWorkDay];
    
    //获取cookie
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie *tempCookie in cookies) {
        //打印获得的cookie
        NSLog(@"getCookie: %@", tempCookie);
    }
    
    // 判断是否登陆过
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    NSString *cookieName = [userdef valueForKey:YAYILoginCookieKey];
    
    if (!cookieName) {
        YAYILoginViewController *loginView = [YAYILoginViewController new];
        loginView.userInfoModel = self.userInfoModel;
//        loginView.loginSuccessOperation = ^(){
//            YAYILog(@"登陆成功");
//            [self createDataSource];
//            
//        };
        
        loginView.cancelOperation = ^(){
            YAYILog(@"取消登陆");
            [self.tabBarController setSelectedIndex:0];
        };
        
        YAYINavigationController *nav = [[YAYINavigationController alloc] initWithRootViewController:loginView];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        //        [self createDataSource];
    }
}


- (void)setupSection0
{
    __block typeof(self) weakself = self;
    
    YAYISettingItemModel *item1 = [[YAYISettingItemModel alloc]init];
    item1.name = @"头像";
    item1.executeOperation = ^(NSIndexPath *indexPath){
        
        YAYIPersoninfoViewController *personinfoVc = [[YAYIPersoninfoViewController alloc] init];
        // 调用刷新界面
        personinfoVc.refreshOperation = ^{
            YAYILog(@"调用刷新界面");
            [weakself createDataSource];
        };
        
        [weakself.navigationController pushViewController:personinfoVc animated:YES];
    };
    
    item1.icon = @"";
//    item1.accessoryType = YAYISettingAccessoryTypeDisclosureIndicator;
    
    YAYISettingSectionModel *section0 = [[YAYISettingSectionModel alloc]init];
    section0.sectionHeaderHeight = 18;
    section0.itemArray = @[item1];
    
    [self.sectionArray addObject:section0];
}


- (void)setupSection1
{
    __block typeof(self) weakself = self;
    
    YAYISettingItemModel *item0 = [YAYISettingItemModel itemWithIcon:@"personnelCenter1" name:@"排班管理" detail:@"暂无排班请开启"];
    item0.executeOperation = ^(NSIndexPath *indexPath){

        // 判断是否实名认真、是否提交过简历 @[@"去实名认证", @"审核中", @"已认证", @"认证失败"];
        if (self.userInfoModel.v == 2) { // 已认证
            
            YAYISchedulingViewController *scheduling = [YAYISchedulingViewController new];
            [weakself.navigationController pushViewController:scheduling animated:YES];
        }else if (self.userInfoModel.v == 1){ // 审核中
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"实名认证审核中，请耐心等待或联系客服。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            
            NSString *alertStr = self.userInfoModel.v == 0 ? @"您还未实名认证，现在去实名认证？" : @"实名认证失败，是否重新提交认证？";
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:alertStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = AlertTypeNotVerify;
            [alert show];
        }
    };
    
    YAYISettingItemModel *item2 = [YAYISettingItemModel itemWithIcon:@"personnelCenter3" name:@"我的业绩"];
    item2.executeOperation = ^(NSIndexPath *indexPath){
        
        // 判断是否实名认真、是否提交过简历 @[@"去实名认证", @"审核中", @"已认证", @"认证失败"];
        if (self.userInfoModel.v == 2) { // 已认证
            
            YAYIPerformanceViewController *performanceVc = [YAYIPerformanceViewController new];
            [weakself.navigationController pushViewController:performanceVc animated:YES];
        }else if (self.userInfoModel.v == 1){ // 审核中
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"实名认证审核中，请耐心等待或联系客服。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            
            NSString *alertStr = self.userInfoModel.v == 0 ? @"您还未实名认证，现在去实名认证？" : @"实名认证失败，是否重新提交认证？";
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:alertStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = AlertTypeNotVerify;
            [alert show];
        }
    };
    
    
    YAYISettingItemModel *item3 = [YAYISettingItemModel itemWithIcon:@"personnelCenter4" name:@"最新点评"];
    item3.destVcClass = [YAYIUserCommentController class];
    
    
    YAYISettingSectionModel *section1 = [[YAYISettingSectionModel alloc]init];
    section1.sectionHeaderHeight = 18;
    section1.itemArray = @[item0, item2, item3];
    
    [self.sectionArray addObject:section1];
}


- (void)setupSection2
{
    
    __block typeof(self) weakself = self;
    
    YAYISettingItemModel *item0 = [YAYISettingItemModel itemWithIcon:@"personnelCenter5" name:@"我的医院"];
    item0.destVcClass = [YAYIMyHospitalViewController class];
    
    YAYISettingItemModel *item1 = [YAYISettingItemModel itemWithIcon:@"personnelCenter6" name:@"我的二维码名片"];
//    item1.destVcClass = [YAYIMyQRCodeViewController class];
    item1.executeOperation = ^(NSIndexPath *indexPath){
    
        YAYIMyQRCodeViewController *qrCoceVc = [[YAYIMyQRCodeViewController alloc] init];
        qrCoceVc.userInfoModel = weakself.userInfoModel;
        [weakself.navigationController pushViewController:qrCoceVc animated:YES];
    };
    
    YAYISettingItemModel *item2 = [YAYISettingItemModel itemWithIcon:@"personnelCenter2_3" name:@"我的简历"];
//    item2.destVcClass = [YAYIAddResumeController class];
    item2.executeOperation = ^(NSIndexPath *indexPath){
        
        // 判断是否实名认真、是否提交过简历 @[@"去实名认证", @"审核中", @"已认证", @"认证失败"];
        if (self.userInfoModel.v == 2) { // 已认证
            
            if (self.myResumeState == 1) { // 有简历，为0则没有简历
                YAYIResumeViewController *resumeVc = [[YAYIResumeViewController alloc] init];
                [weakself.navigationController pushViewController:resumeVc animated:YES];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您还没有简历，是否现在创建？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alert.tag = AlertTypeNoResume;
                [alert show];
            }
        }else if (self.userInfoModel.v == 1){ // 审核中
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"实名认证审核中，请耐心等待或联系客服。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
        
            NSString *alertStr = self.userInfoModel.v == 0 ? @"您还未实名认证，现在去实名认证？" : @"实名认证失败，是否重新认证？";
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:alertStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = AlertTypeNotVerify;
            [alert show];
        }
    };
    
    YAYISettingItemModel *item3 = [YAYISettingItemModel itemWithIcon:@"personnelCenter2_4" name:@"投递记录"];
    item3.destVcClass = [YAYISendResumeListViewController class];
    
    
    YAYISettingSectionModel *section2 = [[YAYISettingSectionModel alloc]init];
    section2.sectionHeaderHeight = 18;
    section2.itemArray = @[item0, item1, item2, item3];
    
    [self.sectionArray addObject:section2];
}


- (void)setupSection3
{
    YAYISettingItemModel *item0 = [YAYISettingItemModel itemWithIcon:@"personnelCenter7" name:@"设置"];
    __block typeof(self) weakself = self;
    item0.executeOperation = ^(NSIndexPath *indexPath){

        YAYIAppSettingViewController *settingVc = [[YAYIAppSettingViewController alloc] init];
        
        // 调用登录界面
        settingVc.loginOperation = ^{
            YAYILog(@"调用登录界面");
            
            [weakself createDataSource];
        };
        
        [weakself.navigationController pushViewController:settingVc animated:YES];
        
    };
    
    
    YAYISettingSectionModel *section3 = [[YAYISettingSectionModel alloc]init];
    section3.sectionHeaderHeight = 18;
    section3.itemArray = @[item0];
    
    [self.sectionArray addObject:section3];
}


- (void)loginStateChanged:(NSNotification *)notify
{
    YAYILog(@"notify:%@", notify);
    
    // 刷新表格
    [self createDataSource];
}


#pragma mark - 获取数据
- (void)createDataSource
{
    // 显示菊花
//    [SVProgressHUD show];
    
    [YAYINetWorking getWithURL:me_personalinfo param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            YAYIUserinfoModel *userInfoModel = [[YAYIUserinfoModel alloc] init];
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                //                return;
            }else{

                [userInfoModel setValuesForKeysWithDictionary:dict[@"data"]];
                
                if (userInfoModel.v == 2) {
                    // 获取简历状态
                    [self getResume];
                }else{
                    // 取出数据模型
                    YAYISettingSectionModel *sectionModel = self.sectionArray[2];
                    YAYISettingItemModel *itemModel = sectionModel.itemArray[2];
                    itemModel.isShowSignal = YES;
                    itemModel.detail = nil;
                    
//                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:2];
//                    YAYISettingCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//                    cell.isShowSignal = NO;
                    
                    [self getResume];
                }
            }
            
            self.userInfoModel = userInfoModel;
            
            YAYISettingSectionModel *section = self.sectionArray[0];
            YAYISettingItemModel *item = section.itemArray[0];
            
            // 姓名
            item.name = userInfoModel.fullname;//dict[@"map"][@"fullname"];
            item.detail = userInfoModel.title;
            
            YAYILog(@"title:%@", userInfoModel.fullname);
            // 头像
            item.icon = userInfoModel.avatar;
            
            NSString *iconUrlStr = [NSString stringWithFormat:@"%@%@", API, userInfoModel.avatar];
            
            if (userInfoModel.avatar) {
                NSUserDefaults *userdef = [NSUserDefaults standardUserDefaults];
                [userdef setValue:iconUrlStr forKey:YAYIHeadKey];
//                [userdef synchronize];
            }
            
            // 实名认证
            //userInfoModel.v == 0;
            NSArray *titleArray = @[@"去实名认证", @"审核中", @"已认证", @"认证失败"];
            // 判断实名认证情况
//            if (userInfoModel.v == 0) {
            
                item.isShowSignal = YES;
                item.signalStr = titleArray[userInfoModel.v];
//            }
            // 保存认证信息
            // 认证标志(0、未提交，1、待处理，2、已认证，3、认证失败)
            NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
            [userdef setInteger:userInfoModel.v forKey:YAYIVerifyState];
            [userdef synchronize];
            
            NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:0 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath1] withRowAnimation:UITableViewRowAnimationNone];
            
            
        }
        
        [SVProgressHUD dismiss];
    }];
    
}


/**
 *  获取是否有排班
 */
- (void)getIsHasWorkDay
{
    // 显示菊花
    //    [SVProgressHUD show];
    
    [YAYINetWorking getWithURL:hasWorkDay_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (!dict || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                return;
            }
            
            NSInteger workdayCount = [dict[@"data"] integerValue];

            // 取出数据模型
            YAYISettingSectionModel *sectionModel = self.sectionArray[1];
            YAYISettingItemModel *itemModel = sectionModel.itemArray[0];
            itemModel.isShowSignal = !(workdayCount > 0);
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
            YAYISettingCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.isShowSignal = !(workdayCount > 0);
        }
        
        [SVProgressHUD dismiss];
    }];
    
}


- (void)getResume
{
    [YAYINetWorking getWithURL:resumeInfo_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"返回:%@", dict);
        
        if (error == nil) {
            
            NSArray *titleArray = @[@"审核中", @"通过审核", @"审核失败", @"未创建"];
            
            // "v": 简历审核标志（0：审核中；1：通过审核；2：审核失败）
            NSInteger state = [dict[@"map"][@"state"] integerValue];
            self.myResumeState = state;
            NSString *signalStr = @"";
            if (state == 1) { // 有简历，为0则没有简历
                
                NSInteger v = [dict[@"data"][@"v"] integerValue];
                self.myResumeV = v;
                signalStr = titleArray[v];
            }else{
                
                signalStr = titleArray[3];
            }
            
            // 取出数据模型
            YAYISettingSectionModel *sectionModel = self.sectionArray[2];
            YAYISettingItemModel *itemModel = sectionModel.itemArray[2];
            itemModel.isShowSignal = YES;
            itemModel.detail = signalStr;
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:2];
            YAYISettingCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            
            cell.isShowSignal = YES;
            cell.tipLbl.text = signalStr;
        }
        
        [self.tableView reloadData];
    }];
}


#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        return 90;
    }
    
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 取出数据模型
    YAYISettingSectionModel *sectionModel = self.sectionArray[indexPath.section];
    YAYISettingItemModel *itemModel = sectionModel.itemArray[indexPath.row];
    
    if (indexPath.section == 0) {
        YAYIMeHeadCell *cell = [YAYIMeHeadCell cellWith:tableView];
        cell.model = itemModel;
        return cell;
    }
    
    YAYISettingCell *cell = [YAYISettingCell cellWith:tableView];
    cell.model = itemModel;
    if (SystemVersion >= 8.0) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    return cell;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (AlertTypeNotVerify == alertView.tag && 1 == buttonIndex) {
        
        YAYICertificationViewController *certifyVc = [[YAYICertificationViewController alloc] init];
        [self.navigationController pushViewController:certifyVc animated:YES];
    }else if (AlertTypeNoResume == alertView.tag && 1 == buttonIndex){
    
        YAYIAddResumeController *resumeVc = [[YAYIAddResumeController alloc] init];
        [self.navigationController pushViewController:resumeVc animated:YES];
    }
}


@end
